import { ref, computed, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useWebRtcPlayer } from './useWebRtcPlayer'
import { useWebSocketPlayer } from './useWebSocketPlayer'

// 播放器管理
export function usePlayerManager({
  isPageActive,
  streamUrl = 'rtsp://stream.strba.sk:1935/strba/VYHLAD_JAZERO.stream'
} = {}) {
  // 状态定义
  const playerMode = ref('webrtc') // 播放模式：'webrtc' 或 'websocket'
  const isWebSocketPlayerActive = ref(false) // WebSocket播放器组件显示状态
  const streamUrlRef = ref(streamUrl) // 流地址
  const playerError = ref(null) // 播放错误
  const isPlaying = ref(false) // 播放状态

  // 初始化播放器
  const webRtcPlayer = useWebRtcPlayer({ streamUrl: streamUrlRef })
  const webSocketPlayer = useWebSocketPlayer({ streamUrl: streamUrlRef })

  // 当前活动播放器
  const activePlayer = computed(() => (playerMode.value === 'webrtc' ? webRtcPlayer : webSocketPlayer))

  // 获取对应模式的播放器
  const getPlayerByMode = (mode) => (mode === 'webrtc' ? webRtcPlayer : webSocketPlayer)

  // 显示错误消息
  const showError = (err) => {
    const errorMsg = err?.message || err || '播放失败'
    playerError.value = errorMsg
    message.error(`播放失败: ${errorMsg}`)
    isPlaying.value = false
  }

  // 停止当前播放器
  const stopCurrentPlayer = () => {
    if (playerMode.value === 'webrtc') {
      webRtcPlayer.stopStream()
    } else {
      webSocketPlayer.stopStream()
      isWebSocketPlayerActive.value = false
    }
  }

  // 播放视频流
  const playStream = async () => {
    playerError.value = null

    if (!streamUrlRef.value?.trim()) {
      showError('请输入有效的视频流地址！')
      return
    }

    isPlaying.value = true

    try {
      if (playerMode.value === 'websocket') {
        isWebSocketPlayerActive.value = true
        await nextTick()
      }

      const result = await activePlayer.value.playStream()
      if (!result) {
        isPlaying.value = false
      }
    } catch (error) {
      showError(error)
    }
  }

  // 停止播放
  const stopPlaying = () => {
    stopCurrentPlayer()
    isPlaying.value = false
  }

  // 处理播放模式变更
  const handlePlayerModeChange = () => {
    const oldMode = playerMode.value === 'webrtc' ? 'websocket' : 'webrtc'
    const wasPlaying = getPlayerByMode(oldMode).isPlaying()

    if (wasPlaying) {
      // 停止旧的播放器，而不是当前播放器
      getPlayerByMode(oldMode).stopStream()
      // 打印日志
      if (oldMode === 'websocket') {
        isWebSocketPlayerActive.value = false
      }
      setTimeout(playStream, 100)
    } else {
      isPlaying.value = false

      if (playerMode.value === 'websocket') {
        isWebSocketPlayerActive.value = false
      }
    }
  }

  // 监听 isPageActive 变化，自动控制播放/停止
  let lastPlayingState = false
  watch(isPageActive, (active) => {
    if (active) {
      if (lastPlayingState) {
        playStream()
      }
    } else {
      lastPlayingState = isPlaying.value
      stopPlaying()
    }
  })

  // 清理资源
  const cleanupPlayers = stopCurrentPlayer

  return {
    playerMode,
    isWebSocketPlayerActive,
    streamUrl: streamUrlRef,
    playerError,
    isPlaying,
    playStream,
    stopPlaying,
    handlePlayerModeChange,
    cleanupPlayers
  }
}
